<template>
  <div class="profile-page">
    <div class="page-header">
      <div class="container">
        <h1 class="page-title">管理员个人中心</h1>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/portal' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>系统管理</el-breadcrumb-item>
          <el-breadcrumb-item>个人中心</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>
    
    <div class="container main-content">
      <el-row :gutter="20" v-loading="loading">
        <!-- 左侧个人信息卡片 -->
        <el-col :xs="24" :sm="24" :md="8" :lg="6" :xl="6">
          <div class="user-card">
            <div class="user-avatar">
              <el-avatar :size="100" :src="userAvatar">
                {{ userStore.name?.charAt(0) || userStore.username?.charAt(0) || '管' }}
              </el-avatar>
            </div>
            <h2 class="user-name">{{ userStore.name || userStore.username }}</h2>
            <p class="user-role">系统管理员</p>
            <div class="admin-info">
              <p><el-icon><Timer /></el-icon> 上次登录: {{ formatDate(adminInfo.lastLoginTime) || '未知' }}</p>
              <p><el-icon><User /></el-icon> 账号创建: {{ formatDate(adminInfo.createdAt) || '未知' }}</p>
            </div>
            <div class="user-stats">
              <div class="stat-item">
                <div class="stat-value">{{ adminStats.users || 0 }}</div>
                <div class="stat-label">用户总数</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ adminStats.doctors || 0 }}</div>
                <div class="stat-label">医生数量</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ adminStats.patients || 0 }}</div>
                <div class="stat-label">患者数量</div>
              </div>
            </div>
          </div>
          
          <!-- 快速链接 -->
          <div class="quick-links">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>系统管理</span>
                </div>
              </template>
              <div class="link-list">
                <div class="link-item" @click="navigateTo('/system/users')">
                  <el-icon><User /></el-icon>
                  <span>用户管理</span>
                </div>
                <div class="link-item" @click="navigateTo('/system/roles')">
                  <el-icon><Lock /></el-icon>
                  <span>角色管理</span>
                </div>
                <div class="link-item" @click="navigateTo('/system/departments')">
                  <el-icon><OfficeBuilding /></el-icon>
                  <span>科室管理</span>
                </div>
                <div class="link-item" @click="navigateTo('/statistics/overview')">
                  <el-icon><TrendCharts /></el-icon>
                  <span>统计报表</span>
                </div>
              </div>
            </el-card>
          </div>
        </el-col>
        
        <!-- 右侧信息和设置 -->
        <el-col :xs="24" :sm="24" :md="16" :lg="18" :xl="18">
          <el-tabs>
            <!-- 个人资料标签页 -->
            <el-tab-pane label="基本资料">
              <el-card class="info-card">
                <template #header>
                  <div class="card-header">
                    <span>基本信息</span>
                    <el-button type="primary" @click="editMode = !editMode">
                      {{ editMode ? '取消编辑' : '编辑信息' }}
                    </el-button>
                  </div>
                </template>
                
                <el-form 
                  :model="adminForm" 
                  :rules="adminRules" 
                  ref="adminFormRef"
                  label-width="100px"
                  :disabled="!editMode"
                >
                  <el-form-item label="用户名" prop="username">
                    <el-input v-model="adminForm.username" disabled></el-input>
                  </el-form-item>
                  <el-form-item label="姓名" prop="name">
                    <el-input v-model="adminForm.name"></el-input>
                  </el-form-item>
                  <el-form-item label="联系电话" prop="phone">
                    <el-input v-model="adminForm.phone"></el-input>
                  </el-form-item>
                  <el-form-item label="电子邮箱" prop="email">
                    <el-input v-model="adminForm.email"></el-input>
                  </el-form-item>
                  <el-form-item label="个人简介" prop="description">
                    <el-input type="textarea" v-model="adminForm.description" rows="4"></el-input>
                  </el-form-item>
                  <el-form-item v-if="editMode">
                    <el-button type="primary" @click="updateAdminInfo">保存信息</el-button>
                    <el-button @click="resetForm">重置</el-button>
                  </el-form-item>
                </el-form>
              </el-card>
            </el-tab-pane>
            
            <!-- 安全设置标签页 -->
            <el-tab-pane label="安全设置">
              <el-card class="info-card">
                <template #header>
                  <div class="card-header">
                    <span>修改密码</span>
                  </div>
                </template>
                
                <el-form 
                  :model="passwordForm" 
                  :rules="passwordRules" 
                  ref="passwordFormRef"
                  label-width="120px"
                >
                  <el-form-item label="当前密码" prop="oldPassword">
                    <el-input 
                      v-model="passwordForm.oldPassword" 
                      type="password" 
                      show-password
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="新密码" prop="newPassword">
                    <el-input 
                      v-model="passwordForm.newPassword" 
                      type="password" 
                      show-password
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="确认新密码" prop="confirmPassword">
                    <el-input 
                      v-model="passwordForm.confirmPassword" 
                      type="password" 
                      show-password
                    ></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="changePassword">修改密码</el-button>
                    <el-button @click="resetPasswordForm">重置</el-button>
                  </el-form-item>
                </el-form>
              </el-card>
              
              <!-- 账号安全设置 -->
              <el-card class="info-card mt-20">
                <template #header>
                  <div class="card-header">
                    <span>账号安全</span>
                  </div>
                </template>
                
                <el-form label-width="150px">
                  <el-form-item label="双因素认证">
                    <el-switch
                      v-model="securitySettings.twoFactorAuth"
                      :disabled="!editSecurityMode"
                    ></el-switch>
                    <el-button 
                      type="text" 
                      style="margin-left: 15px;"
                      @click="editSecurityMode = !editSecurityMode"
                    >
                      {{ editSecurityMode ? '完成' : '修改' }}
                    </el-button>
                  </el-form-item>
                  <el-form-item label="账号登录通知">
                    <el-switch
                      v-model="securitySettings.loginNotification"
                      :disabled="!editSecurityMode"
                    ></el-switch>
                  </el-form-item>
                  <el-form-item label="IP限制">
                    <el-switch
                      v-model="securitySettings.ipRestriction"
                      :disabled="!editSecurityMode"
                    ></el-switch>
                  </el-form-item>
                  <el-form-item v-if="editSecurityMode">
                    <el-button type="primary" @click="updateSecuritySettings">保存安全设置</el-button>
                  </el-form-item>
                </el-form>
              </el-card>
            </el-tab-pane>
            
            <!-- 系统日志标签页 -->
            <el-tab-pane label="操作日志">
              <el-card class="info-card">
                <template #header>
                  <div class="card-header">
                    <span>最近操作日志</span>
                    <el-button type="primary" @click="refreshLogs">刷新</el-button>
                  </div>
                </template>
                
                <el-table :data="activityLogs" style="width: 100%" v-loading="logsLoading">
                  <el-table-column prop="time" label="时间" width="180" />
                  <el-table-column prop="action" label="操作" width="180" />
                  <el-table-column prop="description" label="描述" />
                  <el-table-column prop="ip" label="IP地址" width="150" />
                  <el-table-column prop="status" label="状态" width="100">
                    <template #default="scope">
                      <el-tag :type="scope.row.status === 'success' ? 'success' : 'danger'">
                        {{ scope.row.status === 'success' ? '成功' : '失败' }}
                      </el-tag>
                    </template>
                  </el-table-column>
                </el-table>
                
                <div class="pagination-container">
                  <el-pagination
                    background
                    layout="prev, pager, next"
                    :total="totalLogs"
                    :page-size="10"
                    @current-change="handleLogPageChange"
                  />
                </div>
              </el-card>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { format } from 'date-fns'
import { authAPI, adminAPI, logAPI } from '@/utils/api'
import { 
  User, 
  Lock, 
  TrendCharts, 
  OfficeBuilding, 
  Timer, 
  Setting
} from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)
const logsLoading = ref(false)
const editMode = ref(false)
const editSecurityMode = ref(false)
const adminFormRef = ref(null)
const passwordFormRef = ref(null)

// 用户头像
const userAvatar = computed(() => {
  return userStore.avatar || ''
})

// 管理员信息
const adminInfo = reactive({
  id: '',
  name: '',
  lastLoginTime: null,
  createdAt: null
})

// 统计数据
const adminStats = reactive({
  users: 0,
  doctors: 0,
  patients: 0
})

// 管理员表单数据
const adminForm = reactive({
  username: '',
  name: '',
  phone: '',
  email: '',
  description: ''
})

// 密码表单数据
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 安全设置
const securitySettings = reactive({
  twoFactorAuth: false,
  loginNotification: true,
  ipRestriction: false
})

// 活动日志
const activityLogs = ref([])
const totalLogs = ref(0)
const currentLogsPage = ref(1)

// 表单验证规则
const adminRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入电子邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的电子邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 密码验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不少于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 日期格式化
const formatDate = (date) => {
  if (!date) return '未知'
  return format(new Date(date), 'yyyy-MM-dd HH:mm:ss')
}

// 获取管理员信息
const getAdminInfo = async () => {
  try {
    loading.value = true
    
    // 从store中获取用户ID
    const userId = userStore.userInfo?.id || userStore.userInfo?._id
    
    if (!userId) {
      ElMessage.warning('获取用户信息失败，请重新登录')
      return
    }
    
    // 获取管理员详细信息
    const res = await adminAPI.getAdminInfo(userId)
    
    if (res.success && res.data) {
      // 更新管理员信息
      const data = res.data
      Object.assign(adminInfo, {
        id: data.id || data._id,
        name: data.name || userStore.name,
        lastLoginTime: data.lastLoginTime,
        createdAt: data.createdAt
      })
      
      // 填充表单数据
      Object.assign(adminForm, {
        username: userStore.username || '',
        name: adminInfo.name || userStore.name || '',
        phone: data.phone || '',
        email: data.email || userStore.userInfo?.email || '',
        description: data.description || ''
      })
      
      // 安全设置
      if (data.securitySettings) {
        Object.assign(securitySettings, data.securitySettings)
      }
      
      // 获取统计数据
      loadAdminStats()
      
      // 获取操作日志
      loadActivityLogs()
    } else {
      // 如果API没有返回管理员信息，使用默认值
      ElMessage.warning('无法获取管理员信息，将使用基本用户信息')
      adminInfo.name = userStore.name || userStore.username
      adminForm.username = userStore.username || ''
      adminForm.name = userStore.name || ''
      adminForm.email = userStore.userInfo?.email || ''
      
      // 获取默认统计数据和日志
      loadMockData()
    }
  } catch (error) {
    console.error('获取管理员信息失败:', error)
    ElMessage.error('获取管理员信息失败')
    loadMockData()
  } finally {
    loading.value = false
  }
}

// 加载模拟数据
const loadMockData = () => {
  // 模拟统计数据
  adminStats.users = Math.floor(Math.random() * 100) + 100
  adminStats.doctors = Math.floor(Math.random() * 50) + 20
  adminStats.patients = Math.floor(Math.random() * 100) + 50
  
  // 模拟操作日志
  const mockLogs = []
  const actions = ['登录系统', '创建用户', '修改角色', '更新科室', '查看统计']
  const ips = ['192.168.1.1', '127.0.0.1', '10.0.0.1', '172.16.0.1']
  
  for (let i = 0; i < 10; i++) {
    const date = new Date()
    date.setHours(date.getHours() - i)
    
    mockLogs.push({
      id: `log-${i}`,
      time: formatDate(date),
      action: actions[Math.floor(Math.random() * actions.length)],
      description: `管理员${adminForm.name || '用户'}进行了操作`,
      ip: ips[Math.floor(Math.random() * ips.length)],
      status: Math.random() > 0.2 ? 'success' : 'failed'
    })
  }
  
  activityLogs.value = mockLogs
  totalLogs.value = 100
}

// 加载管理员统计数据
const loadAdminStats = async () => {
  try {
    const res = await adminAPI.getSystemStats()
    
    if (res.success && res.data) {
      Object.assign(adminStats, {
        users: res.data.totalUsers || 0,
        doctors: res.data.totalDoctors || 0,
        patients: res.data.totalPatients || 0
      })
    } else {
      // 使用模拟数据
      adminStats.users = Math.floor(Math.random() * 100) + 100
      adminStats.doctors = Math.floor(Math.random() * 50) + 20
      adminStats.patients = Math.floor(Math.random() * 100) + 50
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    // 使用模拟数据
    adminStats.users = Math.floor(Math.random() * 100) + 100
    adminStats.doctors = Math.floor(Math.random() * 50) + 20
    adminStats.patients = Math.floor(Math.random() * 100) + 50
  }
}

// 加载操作日志
const loadActivityLogs = async (page = 1) => {
  try {
    logsLoading.value = true
    currentLogsPage.value = page
    
    const res = await logAPI.getActivityLogs({
      page,
      limit: 10,
      userId: adminInfo.id
    })
    
    if (res.success && res.data) {
      activityLogs.value = res.data.items.map(log => ({
        id: log.id || log._id,
        time: formatDate(log.createdAt),
        action: log.action,
        description: log.description,
        ip: log.ip,
        status: log.status
      }))
      
      totalLogs.value = res.data.total || 0
    } else {
      // 使用模拟数据
      loadMockData()
    }
  } catch (error) {
    console.error('获取操作日志失败:', error)
    loadMockData()
  } finally {
    logsLoading.value = false
  }
}

// 刷新日志
const refreshLogs = () => {
  loadActivityLogs(currentLogsPage.value)
}

// 处理日志分页变化
const handleLogPageChange = (page) => {
  loadActivityLogs(page)
}

// 更新管理员信息
const updateAdminInfo = async () => {
  try {
    await adminFormRef.value.validate()
    
    loading.value = true
    
    // 构建更新数据
    const updateData = {
      name: adminForm.name,
      phone: adminForm.phone,
      email: adminForm.email,
      description: adminForm.description
    }
    
    // 调用API更新管理员信息
    const res = await adminAPI.updateAdminInfo(adminInfo.id, updateData)
    
    if (res.success) {
      ElMessage.success('管理员信息更新成功')
      
      // 更新本地数据
      adminInfo.name = adminForm.name
      
      // 退出编辑模式
      editMode.value = false
      
      // 同时更新用户基本信息
      const userUpdateData = {
        name: adminForm.name,
        email: adminForm.email
      }
      
      await authAPI.updateUserInfo(userUpdateData)
    } else {
      ElMessage.error(res.message || '更新失败')
    }
  } catch (error) {
    console.error('更新管理员信息失败:', error)
    ElMessage.error('更新管理员信息失败')
  } finally {
    loading.value = false
  }
}

// 更新安全设置
const updateSecuritySettings = async () => {
  try {
    loading.value = true
    
    // 调用API更新安全设置
    const res = await adminAPI.updateSecuritySettings(adminInfo.id, securitySettings)
    
    if (res.success) {
      ElMessage.success('安全设置更新成功')
      editSecurityMode.value = false
    } else {
      ElMessage.error(res.message || '更新失败')
    }
  } catch (error) {
    console.error('更新安全设置失败:', error)
    ElMessage.error('更新安全设置失败')
  } finally {
    loading.value = false
  }
}

// 修改密码
const changePassword = async () => {
  try {
    await passwordFormRef.value.validate()
    
    loading.value = true
    
    // 调用API修改密码
    const res = await authAPI.changePassword({
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    })
    
    if (res.success) {
      ElMessage.success('密码修改成功')
      resetPasswordForm()
    } else {
      ElMessage.error(res.message || '密码修改失败')
    }
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error('修改密码失败')
  } finally {
    loading.value = false
  }
}

// 重置表单
const resetForm = () => {
  adminFormRef.value.resetFields()
  
  // 恢复原始数据
  Object.assign(adminForm, {
    username: userStore.username || '',
    name: adminInfo.name || userStore.name || '',
    phone: adminInfo.phone || '',
    email: adminInfo.email || userStore.userInfo?.email || '',
    description: adminInfo.description || ''
  })
}

// 重置密码表单
const resetPasswordForm = () => {
  passwordFormRef.value.resetFields()
}

// 导航到指定页面
const navigateTo = (path) => {
  router.push(path)
}

// 组件挂载时
onMounted(() => {
  // 检查用户是否登录和角色是否为管理员
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/portal/login')
    return
  }
  
  if (userStore.userRole !== 'admin') {
    ElMessage.warning('只有管理员可以访问此页面')
    router.push('/portal')
    return
  }
  
  // 获取管理员信息
  getAdminInfo()
})
</script>

<style scoped>
.profile-page {
  background-color: #f5f7fa;
  min-height: 100vh;
  padding-bottom: 40px;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  background-color: white;
  padding: 20px 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  margin-bottom: 30px;
}

.page-title {
  font-size: 24px;
  color: #333;
  margin: 0 0 10px;
}

.main-content {
  margin-bottom: 40px;
}

.user-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 30px 20px;
  text-align: center;
  margin-bottom: 20px;
}

.user-avatar {
  margin-bottom: 15px;
}

.user-name {
  font-size: 20px;
  font-weight: 500;
  margin: 0 0 5px;
}

.user-role {
  color: #409EFF;
  font-size: 16px;
  margin: 0 0 15px;
}

.admin-info {
  margin: 15px 0;
  text-align: left;
}

.admin-info p {
  margin: 8px 0;
  display: flex;
  align-items: center;
}

.admin-info .el-icon {
  margin-right: 8px;
  color: #409EFF;
}

.user-stats {
  display: flex;
  justify-content: space-around;
  margin: 20px 0 10px;
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.quick-links {
  margin-bottom: 20px;
}

.link-list {
  display: flex;
  flex-direction: column;
}

.link-item {
  display: flex;
  align-items: center;
  padding: 15px 10px;
  cursor: pointer;
  transition: all 0.3s;
  border-bottom: 1px solid #f5f5f5;
}

.link-item:last-child {
  border-bottom: none;
}

.link-item:hover {
  background-color: #f0f9ff;
  color: #409EFF;
}

.link-item .el-icon {
  font-size: 18px;
  margin-right: 10px;
  color: #409EFF;
}

.info-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.mt-20 {
  margin-top: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

@media (max-width: 768px) {
  .user-card {
    margin-bottom: 20px;
  }
}
</style> 